package co.edu.usbcali.unidades.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.sql.Connection;
import java.util.HashMap;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import co.edu.usbcali.unidades.modelo.Factura;
import co.edu.usbcali.unidades.modelo.Usuario;
import co.edu.usbcali.unidades.utilities.FacesUtils;
import co.edu.usbcali.unidades.utilities.GoogleTest;

import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRPdfExporter;

public class ServletFactura extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public ServletFactura() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			ejecutar(request, response);
		} catch (Exception e) {
			
			e.printStackTrace();
		}

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			ejecutar(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void init() throws ServletException {
		// Put your code here

	}

	public void ejecutar(HttpServletRequest request,HttpServletResponse response) throws Exception {
		
		List<Factura> facturas = (List<Factura>)request.getSession().getAttribute("facturas");
		
		for (int i = 0; i < facturas.size(); i++) {
			//System.out.println(facturas.get(i).getPropietarioInmueble().getPersona().getPerCorreo());
		
		// lista para pasarle el parametro
		HashMap<String, Object> parametros = new HashMap<String, Object>();
		parametros.put("codFac", new String(facturas.get(i).getFacCodigo()));

		// Ruta donde estan los reportes .jasper
		String rutaReportes = getServletContext().getRealPath("/Reportes");

		// pedir la conexion a la base de datos
		Context initialContex = new InitialContext();
		DataSource ds = (DataSource) initialContex.lookup("java:/comp/env/jdbc/Proyecto");
		Connection con = ds.getConnection();

		// Nombre del reporte principal
		FileInputStream fi = new FileInputStream(rutaReportes+ "/factura.jasper");

		//JasperPrint jasper = JasperFillManager.fillReport(fi, parametros, con);
		JasperPrint jasper = JasperFillManager.fillReport(fi, parametros, con);

		//response.setContentType("application/pdf");
		// guardar como
		//response.setHeader("content-disposition","attachment; filename=\"factura"+i+".pdf\"");
		// si el cliente los soporta
		//response.setHeader("content-disposition","inline; filename=\"reporte.pdf\"");

		// para bajar el archivo a pdf
		File archivoGenerado = new File(rutaReportes + "factura"+i+".pdf");		
		FileOutputStream fos = new FileOutputStream(archivoGenerado);
		
		JRPdfExporter exporter = new JRPdfExporter();
		exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasper);
		exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, fos);
		exporter.exportReport();
		
		fos.close();
		
		GoogleTest g = new GoogleTest();
		g.sendSSLMessage2(new String[]{facturas.get(i).getPropietarioInmueble().getPersona().getPerCorreo()}, 
				"Factura", "","humberto", "humberto.guerrero1@gmail.com", "HAGUERRERO1090630",archivoGenerado);
		
		
		//ServletOutputStream out = response.getOutputStream();
		
		//out.close();
		}
	}
}